﻿<template>
    <full-screen-dialog
        :title="titleMap[mode]"
        v-model="visible"
        :width="1200"
        destroy-on-close
        @closed="$emit('closed')"
    >
        <el-form
            :model="entityObj"
            :rules="rules"
            :disabled="mode == 'Show'"
            ref="dialogForm"
            label-width="100px"
            @keydown="handleKeydown"
        >
            <el-row>
                <el-col :span="24">
                    <el-form-item label-width="130px" label="盘点模版：">
                        <sc-file-import ref="scFileImport" :size="'small'" :importUrl="'stockOrder/import'" @fatherMethod="uploadHandel"></sc-file-import>
                        <el-button type="primary" size="small" plain icon="el-icon-download" @click="opTemplateDownload">模版下载</el-button>
                    </el-form-item>
                    
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item label-width="130px" label="盘点仓库：" prop="warehouseId">
                        <el-select placeholder="---请选择仓库---" v-model="entityObj.warehouseId" style="width: 100%" :disabled="true">
                            <el-option label="---请选择仓库---" value="" />
                            <el-option v-for="item in optionsWarehouse" :key="item.warehouseId" :label="item.warehouseName" :value="item.warehouseId" />
                        </el-select>
                    </el-form-item>
                </el-col>
               
            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item label-width="130px" label="计划盘点时间：" prop="stockDates">
                        <el-date-picker v-model="entityObj.stockDates" type="datetimerange"  style="width: 100%" :disabled="true"
                            value-format="YYYY-MM-DD HH:mm:ss" start-placeholder="开始日期" end-placeholder="结束日期" :default-time="defaultTime">
                        </el-date-picker>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label-width="130px" label="实际盘点时间：" prop="realStockDate">
                        <el-date-picker v-model="entityObj.realStockDate" type="datetime"  style="width: 100%" 
                            value-format="YYYY-MM-DD HH:mm:ss" placeholder="请填写实际盘点时间" >
                        </el-date-picker>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-form-item label-width="130px" label="盘点说明：">
                        <el-input v-model="entityObj.remarks" type="textarea" :rows="2" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-form-item label-width="130px" label="盘点物料：" prop="name">
                        <el-table 
                            :data="entityObj.items" 
                            style="width: 100%;height: 400px;"  
                            :row-class-name  ="selectedStyle"
                            @row-click="rowClick"
                            border
                            >
                            <el-table-column prop="rowNumber" label="序号" width="65" align="center" fixed="left">
                                <template #default="scope">
                                    {{ scope.$index+1 }}
                                </template>
                            </el-table-column>
                            <el-table-column prop="materialCode" label="物料编码" width="100" />
                            <el-table-column prop="materialTypeName" label="物料分类" width="130" />
                           
                            <el-table-column prop="materialName" label="物料名称" width="200">
                                <template #default="scope">
                                        <div style="color: #318cf2; cursor: pointer;" @click="handlePreview(scope.row)">
                                            {{scope.row.materialName}}
                                        </div>
                                    </template>
                            </el-table-column>
                            <el-table-column prop="materialSpecs" label="规格" width="100" />
                            <el-table-column prop="unitName" label="单位" width="80" />
                            <el-table-column prop="startStockQty" label="起始库存" width="90" />
                            <el-table-column prop="endStockQty" label="账面库存" width="90" />
                            <el-table-column prop="realQty" label="实际盘点" width="90" >
                                <template #default="scope">
                                    <el-input 
                                        :id="'input_realQty_'+scope.$index"
                                        :ref="'input_realQty_'+scope.$index"
                                        v-model="scope.row.realQty" 
                                        style="width: 100%" 
                                        @blur="onRealQtyChange(scope.row)">
                                    </el-input>
                                </template>
                            </el-table-column>
                            <el-table-column prop="profitQty" label="盈亏数量" width="90" >
                                <template #default="scope">

                                    <el-tag v-if="scope.row.profitQty<0" type="success" effect="dark" style="width: 50px;">{{ scope.row.profitQty }}</el-tag>
                                    <el-tag v-else-if="scope.row.profitQty>0" type="danger" effect="dark" style="width: 50px;">+{{ scope.row.profitQty }}</el-tag>
                                    <el-tag v-else-if="scope.row.profitQty==0" color="#FFDE0A"  style="width: 50px;color:white">{{ scope.row.profitQty }}</el-tag>
                                </template>
                            </el-table-column>
                            <el-table-column prop="remarks" label="备注" width="100" >
                                <template #default="scope">
                                    <el-input 
                                        :id="'input_remarks_'+scope.$index"
                                        :ref="'input_remarks_'+scope.$index"
                                        v-model="scope.row.remarks" 
                                        style="width: 100%" 
                                        
                                        >
                                    </el-input>
                                </template>
                            </el-table-column>
                            <el-table-column prop="status" label="状态" width="130" >
                                <template #default="scope">
                                    <el-select v-model="scope.row.status">
                                        <template #prefix> 
                                            <div v-if="scope.row.status==0" style="display:block;"> 
                                                <el-tag color="#67C23A" style="vertical-align:middle;" size="small" />
                                            </div>
                                            <div v-else-if="scope.row.status==1" style="display:block;"> 
                                                <el-tag color="#E63415" style="vertical-align:middle;" size="small" />
                                            </div> 
                                            <div v-else-if="scope.row.status==2" style="display:block;"> 
                                                <el-tag color="#FFDE0A" style="vertical-align:middle;" size="small" />
                                            </div>   
                                        </template>
                                       
                                        <el-option label="盘亏" :value="0">
                                            <div style="display:block;">
                                                <el-tag color="#67C23A" style="margin-right: 8px;vertical-align:middle;" size="small" />
                                                <span>盘亏</span>
                                            </div>
                                        </el-option>
                                        <el-option label="盘赢" :value="1">
                                            <div style="display:block;">
                                                <el-tag color="#E63415" style="margin-right: 8px;vertical-align:middle;" size="small" />
                                                <span>盘赢</span>
                                            </div>
                                        </el-option>
                                        <el-option label="持平" :value="2">
                                            <div style="display:block;">
                                                <el-tag color="#FFDE0A" style="margin-right: 8px;vertical-align:middle;" size="small" />
                                                <span>持平</span>
                                            </div>
                                        </el-option>
                                    </el-select>
                                </template>
                            </el-table-column>
                            <el-table-column label="操作" width="200">
                                <template #default="scope">
                                    <el-link
                                        type="primary"
                                        size="small"
                                        link
                                        @click="opShowFlow(scope.$index, scope.row)"
                                        style="margin-right: 5px;"
                                    ><el-icon style="margin-right: 5px;"><View /></el-icon> 查看出入库流水</el-link>
                                    <el-link
                                        type="danger"
                                        size="small"
                                        link
                                        @click="deleteRow(scope.$index, scope.row)"
                                        style="margin-right: 5px;"
                                    ><el-icon style="margin-right: 5px;"><Delete /></el-icon> 移除</el-link>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-form-item>
                </el-col>
               
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-form-item label-width="130px" label="创建人：">
                        {{entityObj.createName}}
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-form-item label-width="130px" label="创建时间：">
                        {{entityObj.createTime}}
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <template #footer>
            <el-button @click="visible = false">取 消</el-button>
            <el-button
                v-if="mode != 'Show'"
                type="primary"
                :loading="isSaveing"
                @click="submit()"
            >保 存</el-button>
        </template>
        <template-dialog
            v-if="dialogTemplate"
            ref="templateDialog"
            @fatherMethod="opBindData"
            @success="handleSaveSuccess"
            @closed="dialogTemplate = false"
        ></template-dialog>
         <!-- 预览组件 -->
		  <el-image-viewer v-if="showImage" @close="closeViewer" :url-list="srcList" />
    </full-screen-dialog>
</template>

<script>
import tool from "@/utils/tool";
import templateDialog from "./template";
export default {
    emits: ["success", "closed"],
    components: {
        templateDialog
    },
    data() {
        return {
            mode: "Add",
            titleMap: {
                Add: "新增盘点",
                Edit: "编辑盘点",
                Show: "查看盘点",
            },
            entityObj: {
                status: 1,
            },
            visible: false,
            isSaveing: false,
            needSaveFlag: false,
            dialogTemplate: false,
            //验证规则
            rules: {
                stockDates: [
                    {
                        required: true,
                        type: "array",
                        message: "请填写计划盘点时间",
                    },
                ],
                realStockDate: [
                    {
                        required: true,
                        type: "string",
                        message: "请填写实际盘点时间",
                    },
                ],
               
               
            },
            optionsWarehouse: [],
            currentIndex: 0,
            //预览图片
            previewUrl: [],
            //预览图片列表
            srcList: [],
            showImage: false,
            defaultTime:[
                new Date(2000, 1, 1, 0, 0, 0),
                new Date(2000, 2, 1, 23, 59, 59),
            ]
        };
    },
    methods: {
        //显示=
        open(mode = "Add") {
            this.mode = mode;
            this.visible = true;
            return this;
        },
         //模版下载
         opTemplateDownload()
        {
            this.dialogTemplate = true;
            this.$nextTick(() => {
                this.$refs.templateDialog.open("Add");
            });
        },
        //导入成功
        uploadHandel(res)
        {
            console.log("res",res);
            var warehouseObj=this.optionsWarehouse.filter((p)=>p.warehouseName==res.warehouseName);
            
            this.entityObj.warehouseId=warehouseObj[0].warehouseId;
            this.entityObj.stockDates=res.stockDates;
            res.items.map((p) => p.profitQty=p.realQty-p.endStockQty);
            this.entityObj.items=res.items;
        },
        //实际盘点变化
        onRealQtyChange(row)
        {
            var endStockQty=row.endStockQty;
            var realQty=row.realQty;
            console.log("实际盘点值",realQty+"--"+endStockQty);
            row.profitQty=realQty-endStockQty;
        },
         //选中样式
         selectedStyle({ row, rowIndex })
        {
            if (row.profitQty<0) {
                return 'tr-green';
                //return { backgroundColor: '#67C23A',color: 'white'};
            }else if (row.profitQty>0) {
                return 'tr-red';
            }
            return {};
        },
        //行点击
        async rowClick(row) {
            //获取行下标
            this.currentIndex = this.entityObj.items.indexOf(row);
            console.log("获取行下标", this.currentIndex);
        },
        //键盘事件
        handleKeydown(event) {
            console.log("按键", event.target.id);
            var idArr = event.target.id.split("_");
            var prefix = idArr[0] + "_" + idArr[1];
            const keyCode = event.keyCode || event.which;

            if (keyCode === 38) {
                // 上键

                if (this.currentIndex > 0) {
                    this.currentIndex--;
                    if (this.currentIndex <= 0) this.currentIndex = 0;

                    var findInputUp =
                        this.$refs[prefix + "_" + this.currentIndex];
                    this.$nextTick(() => {
                        if (findInputUp) {
                            findInputUp.focus();
                            const len = findInputUp.input.value.length * 2;
                            setTimeout(() => {
                                findInputUp.input.setSelectionRange(len, len);
                            }, 1);
                        }
                    });
                }
            } else if (keyCode === 40) {
                // 下键

                this.currentIndex++;
                if (this.currentIndex >= this.entityObj.items.length) {
                    this.currentIndex =
                        this.entityObj.items.length - 1;
                }

                var findInputDown =
                    this.$refs[prefix + "_" + this.currentIndex];
                this.$nextTick(() => {
                    if (findInputDown) {
                        findInputDown.focus();
                    }
                });
            }
        },
        //表单提交方法
        submit() {
            this.$refs.dialogForm.validate(async (valid) => {
                if (valid) {
                    this.isSaveing = true;
                    const data={ 
                        ...this.entityObj
                    }
                    try {
                        var returnValue =
                            await this.$API.auth.PostProcessApi.post(
                                this.mode == "Add"
                                    ? "stockOrder/create"
                                    : "stockOrder/update",data
                            );
                        if (returnValue.status == 200) {
                            this.$message.success("操作成功");
                            this.$emit("fatherMethod");
                            this.isSaveing = false;
                            this.visible = false;
                        } else {
                            this.$message.error("操作失败:" + returnValue.msg);
                            this.isSaveing = false;
                            this.visible = false;
                        }
                    } catch (error) {
                        this.loading = false;
                        return false;
                    }
                }
            });
        },
        //查看流水
        opShowFlow(index,row)
        {
            var stockOperDates=[this.entityObj.stockDates[1],this.entityObj.realStockDate];
            this.$router.push({ path: '/stockFlow', query: 
            {
                materialCode:row.materialCode, 
                beginTime:this.entityObj.stockDates[1],
                endTime:this.entityObj.realStockDate
            }});
        },
        //删除
        deleteRow(index,row) {
            this.entityObj.items.splice(index, 1);
        },
        async initOptions() {
            try {
                var returnValue = await this.$API.auth.PostProcessApi.post("warehouse/list",{IsExternal:false});
                if (returnValue.status == 200) {
                    console.log("仓库",returnValue.response);
                    this.optionsWarehouse = returnValue.response;
                } else {
                    this.$message.error("操作失败:" + returnValue.msg);
                }
            } catch (error) {
                this.loading = false;
                return false;
            }
        },
        //表单注入数据
        async setData(data) {
            this.entityObj = {
                ...data
            }; 
        },
         //图片预览
			 handlePreview(row) {
				if (!row.materialImages || row.materialImages.length == 0) {
					return;
				}
				this.previewUrl = row.materialImages[0]; // 设置当前预览的图片 URL
				this.srcList = row.materialImages; // 设置预览列表
				this.showImage = true; // 显示 el-image

			},
			closeViewer(){
				this.showImage = false; 
			},
        
    },
    async mounted() {
        await this.initOptions();
        if(this.mode=='Add'){
            this.entityObj.createName = tool.data.get("USER_INFO").Name;
            this.entityObj.createTime = tool.formatDate(new Date());
        }
    },
};
</script>

<style scoped>
/deep/ .el-table .tr-red > td
{
    background-color:#FDEDD7 !important;
    
}
/deep/ .el-table .tr-green > td
{
    background-color:#EFF9EA !important;
    
}
</style>
